package com.skytech.component.monitor.enterprise_data_monitoring;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.WebClient;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.data.MonitorDataDAO;
import com.skytech.component.monitor.data.MonitorDataTag;
import com.skytech.component.monitor.data.MonitorDataTagDAO;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.WebClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class SiChuanService implements CrawlerScript {

    private static final String province = "四川省";
    @Autowired
    private RestTemplateBuilder restTemplateBuilder;
    @Autowired
    private ChromeBrowser chromeBrowser;
    @Autowired
    private MonitorDataTagDAO monitorDataTagDAO;
    @Autowired
    private MonitorDataDAO monitorDataDAO;

    private static final Logger log = LoggerFactory.getLogger(SiChuanService.class);


    @Override
    public void start() {
        String content = restTemplateBuilder.build().getForObject("http://182.148.109.184/page/gis/gisnavigation!getcompanyjson.action", String.class);
        List<JSONObject> jsonObjects = JSONArray.parseArray(content, JSONObject.class);

        String entInfoUrl = "http://182.148.109.184/enterprise-info!getCompanyInfo.action?companyid=";

       /* ChromeDriver chromeDriver = chromeBrowser.getChromeDriver();*/
        ChromeDriver chromeDriver = chromeBrowser.getChromeDriver();
        for (JSONObject jsonObject : jsonObjects) {

            try{
                String entName = jsonObject.getString("full_name");
                String city = jsonObject.getString("codeRegion");
                String orgId = jsonObject.getString("orgId");
                chromeDriver.get(entInfoUrl + orgId);
                Thread.sleep(5000);
                //企业基本信息页面
                String entInfo = chromeDriver.findElementByTagName("html").getAttribute("outerHTML");
                Document parse = Jsoup.parse(entInfo);
                String address = parse.getElementsMatchingOwnText("企业地址：").next().text();
                String industry = parse.getElementsMatchingOwnText("所属行业：").next().text();
                //点击到自动监测页面
                //水
                chromeDriver.findElementsByXPath("//*[@id=\"history\"]/a").get(0).click();
                Thread.sleep(3000);
                String waterKey = orgId+"water";
                page(chromeDriver,"water",entName,address,industry,waterKey,city);
                //todo 解析水

                //todo 翻页

                //*[@id="controls"]/div[1]/img[1]

                //气
                chromeDriver.findElementsByXPath("//*[@id=\"historyform\"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/input[2]").get(0).click();
                chromeDriver.findElementsByXPath("//*[@id=\"historyform\"]/table/tbody/tr/td[2]/img").get(0).click();
                Thread.sleep(3000);
                String gasKey = orgId+"gas";
                page(chromeDriver,"gas",entName,address,industry,gasKey,city);

                //todo 解析气
                //噪声
                /*chromeDriver.findElementsByXPath("//*[@id=\"historyform\"]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[1]/input[3]").get(0).click();
                chromeDriver.findElementsByXPath("//*[@id=\"historyform\"]/table/tbody/tr/td[2]/img").get(0).click();
                Thread.sleep(3000);
                String entNoise = chromeDriver.findElementByTagName("html").getAttribute("outerHTML");*/
                //todo 解析噪声

            }catch (Exception e){
                log.error("解析企业信息发生错误{}",e.getMessage());
            }finally {

            }
        }
        try{
            chromeDriver.quit();
        }catch (Exception e){
            log.error("四川网站关闭页面错误--{}",e.getMessage());
        }

    }
    public void page(ChromeDriver chromeDriver,String pollutionType, String compoanyName, String address,String industry,String key,String city) throws InterruptedException {
        List<MonitorData> allData = new ArrayList<>();
        String entDoc = chromeDriver.findElementByTagName("html").getAttribute("outerHTML");
        Document doc = Jsoup.parse(entDoc);
        String pageNum = doc.select("#historyinfo #pagelimit").text();
        int i = Integer.parseInt(pageNum);
        List<MonitorData> monitorDataList = parseData(chromeDriver, pollutionType, compoanyName, address, industry,city);
        allData.addAll(monitorDataList);
        /*monitorDataDAO.saveAll(monitorDataList);*/
        if(i>2&&monitorDataList.size()>0){
            for(int j = 0;j<i-1;j++){
                chromeDriver.findElementsByXPath("//*[@id=\"controls\"]/div[1]/img[1]").get(0).click();
                Thread.sleep(3000);
                List<MonitorData> monitorDatas = parseData(chromeDriver, pollutionType, compoanyName, address, industry,city);
                allData.addAll(monitorDatas);
                if(!(monitorDatas.size()>0)){
                    break;
                }

            }
        }
        MonitorDataTag tag = new MonitorDataTag();
        tag.setProvince(province);
        tag.setUniqueKey(key);
        List<MonitorDataTag> all = monitorDataTagDAO.findAll(Example.of(tag));
        MonitorDataTag lastTag = new MonitorDataTag();
        if(all.isEmpty()&&!allData.isEmpty()){
            tag.setId(UUID.randomUUID().toString());
            tag.setLabel(monitorDataList.get(0).getMonitorInfo()+monitorDataList.get(0).getMonitorTime());
            monitorDataTagDAO.save(tag);
            monitorDataDAO.saveAll(allData);
        }else{
            for (int i1 = 0; i1 < allData.size(); i1++) {
                if(all.get(0).getLabel().equals(allData.get(i1).getMonitorInfo()+allData.get(i1).getMonitorTime())){
                    break;
                }
                monitorDataDAO.save(allData.get(i1));
            }
            if(!allData.isEmpty()){
                lastTag = all.get(0);
                lastTag.setLabel(monitorDataList.get(0).getMonitorInfo()+monitorDataList.get(0).getMonitorTime());
                monitorDataTagDAO.save(lastTag);
            }
        }
    }

    private List<MonitorData> parseData(ChromeDriver chromeDriver, String pollutionType, String compoanyName, String address,String industry,String city){
        String entDoc = chromeDriver.findElementByTagName("html").getAttribute("outerHTML");
        Document doc = Jsoup.parse(entDoc);
        Element element = doc.select("#noisetables").prev().get(0);
        MonitorData monitorData = null;
        List<MonitorData> list = new ArrayList<>();
        if(element.select("tr").get(1).select("td").size()>1){
            //有数据
            Elements trs = element.select("tr");
            trs.remove(0);
            for (Element tr : trs) {
                monitorData  = new MonitorData();
                Elements tds = tr.select("td");
                monitorData.setMonitorPoint(tds.get(0).text())
                        .setProvince(province)
                        .setPollutionType(pollutionType)
                        .setMonitorInfo(tds.get(2).text())
                        .setMonitorValue(tds.get(4).text())
                        .setMonitorStandardValue(tds.get(5).text())
                        .setMonitorTime(tds.get(1).text())
                        .setAddress(address)
                        .setCompanyName(compoanyName)
                        .setIndustry(industry)
                        .setId(UUID.randomUUID().toString())
                        .setCity(city);
                monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                list.add(monitorData);

            }

        }
        return list;
    }
}
